package com.lst.projectlib.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;

import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.DisplayImageOptions.Builder;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.display.CircleBitmapDisplayer;
import com.nostra13.universalimageloader.core.imageaware.ImageViewAware;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.lst.projectlib.R;

import java.io.File;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ImageLoaderUtil {
	private static ImageLoaderUtil instance;
	private ImageLoaderUtil() {
		super();
	}

	public static ImageLoaderUtil getInstance() {
		if (instance == null) {
			instance = new ImageLoaderUtil();
		}
		return instance;
	}

	protected void init(Context context) {
		//创建ImageLoader配置参数
		ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(context);
		config.threadPriority(Thread.NORM_PRIORITY - 2);
		config.denyCacheImageMultipleSizesInMemory();
		config.diskCacheFileNameGenerator(new Md5FileNameGenerator());
		config.diskCacheSize(50 * 1024 * 1024); // 50 MiB
		//Initialize ImageLoaderUtil with configuration.
		ImageLoader.getInstance().init(config.build());
	}

	public void displayImage(String uri, ImageView imageView, boolean isCircle, int defaultPicId) {
		displayImage(uri, imageView, isCircle, 0, 0, defaultPicId,null);
	}

	public void displayImage(String uri, ImageView imageView, boolean isCircle, int width, int height, int defaultPicId, Builder builder) {
		displayImage(uri, imageView, isCircle, width, height, defaultPicId, builder, null);
	}

	public void displayImage(String uri, ImageView imageView, final boolean isCircle, int width, int height, int defaultPicId, Builder builder, ImageLoadingListener listener) {
		if(builder==null){
			builder = getDisplayImageBuilder();
		}

		int resId = R.drawable.img_loaderror;
		if (isCircle) {
			resId = R.drawable.img_loaderror_circle;
			builder.displayer(new CircleBitmapDisplayer());
		}
		if(defaultPicId >= 0) {
			resId = defaultPicId;
		}
		builder.showImageForEmptyUri(resId)
				.showImageOnFail(resId);
		DisplayImageOptions options = builder.build();

		ImageSize imageSize = null;
		if(width>0 && height>0) {
			imageSize = new ImageSize(width, height);
		}
		ImageLoader.getInstance().displayImage(uri, new ImageViewAware(imageView), options, imageSize, listener, null);
	}

	public Bitmap loadImageSync(String uri, int width, int height, Builder builder) {
		if(builder==null){
			builder = getDisplayImageBuilder();
		}
		DisplayImageOptions options = builder.build();

		ImageSize imageSize = null;
		if(width>0 && height>0) {
			imageSize = new ImageSize(width, height);
		}
		return ImageLoader.getInstance().loadImageSync(uri, imageSize, options);
	}

	public Builder getDisplayImageBuilder(){
		Builder builder = new Builder();
		builder.cacheInMemory(true).cacheOnDisk(true)
				.bitmapConfig(Bitmap.Config.RGB_565); //设置图片的质量
		return builder;
	}

	public File getDiskCacheFile(String url){
		return ImageLoader.getInstance().getDiskCache().get(url);
	}

	/**
	 * 创建线程池，用来顺训执行线程操作
	 */
	private ExecutorService mThreadPool = null;
	private Handler mHandler = null;
	public void displayImage(byte[] btImg, ImageView imageView, boolean isCircle, int defaultId) {
		if (btImg == null || btImg.length == 0) {
			imageView.setImageResource(defaultId);
			return;
		}

		setUseByteBmp();

		MyThread bookChangeThread = new MyThread(imageView,	btImg, isCircle, defaultId);
		mThreadPool.execute(bookChangeThread);
	}

	private class MyThread implements Runnable {
		private ImageView mIvHead = null;
		private byte[] mBtImg = null;
		private int mDefaultId = 0;
		private boolean mIsCircle = false;

		public MyThread(ImageView iv, byte[] btImg, boolean isCircle, int defaultId) {
			mIvHead = iv;
			mBtImg = btImg;
			mDefaultId = defaultId;
			mIsCircle = isCircle;
		}

		@Override
		public void run() {
			Object[] objects = new Object[3];
			objects[1] = mIvHead;
			objects[2] = mDefaultId;

			if (mBtImg != null) {
				Bitmap bmp = BitmapFactory.decodeByteArray(mBtImg, 0, mBtImg.length);
				if (bmp != null) {
					if (mIsCircle) {
						bmp = BitmapUtil.toRoundBitmap(bmp, false);
					}

					objects[0] = bmp;
				}
			}

			Message message = new Message();
			message.obj = objects;
			message.what = 0;
			mHandler.sendMessage(message);
		}
	}

	public void setUseByteBmp() {
		if (mThreadPool == null) {
			mThreadPool = Executors.newSingleThreadExecutor();
			mHandler = new Handler(new Handler.Callback() {
				@Override
				public boolean handleMessage(Message msg) {
					switch (msg.what) {
						case 0:
							if (msg.obj != null && msg.obj instanceof Object[]) {
								Object[] objects = (Object[]) msg.obj;
								if (objects[1] != null
										&& objects[1] instanceof ImageView) {
									ImageView iv = (ImageView) objects[1];

									if (objects[0] != null
											&& objects[0] instanceof Bitmap) {
										iv.setImageBitmap((Bitmap) objects[0]);
									} else {
										iv.setImageResource((Integer) objects[2]);
									}
								}
							}
							return true;
					}
					return false;
				}
			});
		}
	}
}
